import {Injectable} from "@angular/core";
import {Response, Http} from "@angular/http";
import {Observable} from "rxjs";
import {Emoji} from "../components/emoji/emoji";
/**
 * Created by jackbranson on 17/3/11.
 */

@Injectable()
export class EmojiService {
  private static jsonRequestDone: Promise<Response>;

  private static emojiList: any = {};
  private static emojiNameList: any = {};
  private static emojiReservedNameList: any = {};

  constructor(private http: Http) {
    if (Object.keys(EmojiService.emojiList).length !== 0) return;
    EmojiService.jsonRequestDone = new Promise((resolve, reject) => {
      let subscriber = http.get('/assets/emoji/emoji.json');
      subscriber.subscribe(e => {
        resolve(e.json());
      });
      subscriber.catch((e, o) => {
        reject(e);
        return Observable.throw(e);
      });
    });
    EmojiService.jsonRequestDone.then(e => {
      EmojiService.emojiList = e;
      Object.keys(e).map((k) => {
        Object.assign(EmojiService.emojiNameList, e[k]);
      });
      EmojiService.emojiReservedNameList = Object.keys(EmojiService.emojiNameList).reduce(function (obj, key) {
        obj[EmojiService.emojiNameList[key]] = key;
        return obj;
      }, {});
    });
  }

  getEmojiUnicode(emojiChar: string) {
    if (emojiChar.length == 2) return (emojiChar.charCodeAt(0) - 0xD800) * 0x400 + emojiChar.charCodeAt(1) - 0xDC00 + 0x10000;
    return emojiChar.charCodeAt(0);
  }

  escapeEmojiToEmojiElement(str: string) {
    let emoji_re = /(\ud83d[\ude00-\ude4f])/g;
    let match = str.match(emoji_re);
    if (match) {

      match.map(
        (v: string) => {
          str = str.replace(v, `[emoji-${EmojiService.emojiReservedNameList[this.getEmojiUnicode(v).toString(16)]}]`)
        });
    }
    return str;
  }

  getEmojiId(emojiName: string): Promise<string> {
    return new Promise((resolve, reject) => {
      EmojiService.jsonRequestDone.then(e => {
        let emoji_id = EmojiService.emojiNameList[emojiName];
        resolve(emoji_id);
      });
    });
  }

  getEmojiList(): Promise<any> {
    return new Promise((resolve, reject) => {
      EmojiService.jsonRequestDone.then(() => {
        resolve(EmojiService.emojiList);
      });
    })
  }
}
